#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

// 抽象类Shape，包含纯虚函数
class Shape {
public:
    virtual double calculateArea() = 0;
    virtual bool isValid() = 0;
    virtual ~Shape() {}
};

// 长方形类Rectangle
class Rectangle : public Shape {
private:
    double width;
    double height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    double calculateArea() override { return width * height; }
    bool isValid() override { return width > 0 && height > 0; }
};

// 正方形类Square
class Square : public Shape {
private:
    double side;
public:
    Square(double s) : side(s) {}
    double calculateArea() override { return side * side; }
    bool isValid() override { return side > 0; }
};

// 三角形类Triangle
class Triangle : public Shape {
private:
    double base;
    double height;
    double side1;
    double side2;
public:
    Triangle(double b, double h, double s1, double s2) : base(b), height(h), side1(s1), side2(s2) {}
    double calculateArea() override { return 0.5 * base * height; }
    bool isValid() override {
        // 判断三角形是否合法：两边之和大于第三边
        return base > 0 && height > 0 && (base + side1 > side2) && (base + side2 > side1) && (side1 + side2 > base);
    }
};

// 简单工厂类ShapeFactory
class ShapeFactory {
public:
    static Shape* createShape(int type) {
        switch(type) {
            case 0:
                return new Rectangle(rand() % 10 + 1, rand() % 10 + 1);
            case 1:
                return new Square(rand() % 10 + 1);
            case 2:
                return new Triangle(rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1);
            default:
                return nullptr;
        }
    }
};

// 主函数
int main() {
    srand(time(0)); // 初始化随机数生成器
    std::vector<Shape*> shapes;
    double totalArea = 0;

    // 创建10个随机形状对象
    for(int i = 0; i < 10; ++i) {
        int type = rand() % 3; // 随机选择形状类型
        Shape* shape = ShapeFactory::createShape(type);
        if(shape && shape->isValid()) {
            shapes.push_back(shape);
            totalArea += shape->calculateArea();
        } else {
            delete shape; // 如果形状不合法，删除对象
        }
    }

    std::cout << "随机创建的10个合法形状对象的面积之和为: " << totalArea << std::endl;

    // 清理内存
    for(Shape* shape : shapes) {
        delete shape;
    }

    return 0;
}
